class PolicyController {
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ policyInstanceList: Policy.list( params ), policyInstanceTotal: Policy.count() ]
    }

    def show = {
        def policyInstance = Policy.get( params.id )

        if(!policyInstance) {
            flash.message = "Policy not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ policyInstance : policyInstance ] }
    }

    def delete = {
        def policyInstance = Policy.get( params.id )
        if(policyInstance) {
            policyInstance.delete()
            flash.message = "Policy ${params.id} deleted"
            redirect(action:list)
        }
        else {
            flash.message = "Policy not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def policyInstance = Policy.get( params.id )

        if(!policyInstance) {
            flash.message = "Policy not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ policyInstance : policyInstance ]
        }
    }

    def update = {
        def policyInstance = Policy.get( params.id )
        if(policyInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(policyInstance.version > version) {
                    
                    policyInstance.errors.rejectValue("version", "policy.optimistic.locking.failure", "Another user has updated this Policy while you were editing.")
                    render(view:'edit',model:[policyInstance:policyInstance])
                    return
                }
            }
            policyInstance.properties = params
            if(!policyInstance.hasErrors() && policyInstance.save()) {
                flash.message = "Policy ${params.id} updated"
                redirect(action:show,id:policyInstance.id)
            }
            else {
                render(view:'edit',model:[policyInstance:policyInstance])
            }
        }
        else {
            flash.message = "Policy not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def policyInstance = new Policy()
        policyInstance.properties = params
        return ['policyInstance':policyInstance]
    }

    def save = {
        def policyInstance = new Policy(params)
        if(!policyInstance.hasErrors() && policyInstance.save()) {
            flash.message = "Policy ${policyInstance.id} created"
            redirect(action:show,id:policyInstance.id)
        }
        else {
            render(view:'create',model:[policyInstance:policyInstance])
        }
    }
}
